﻿using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Bit.Art.Core.Extensions;
using Bit.Art.Core.Models;
using Bit.Art.Db;
using Bit.Art.Distributed;
using Disruptor.Dsl;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NetMQ;
using NetMQ.Sockets;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.SystemConsole.Themes;

namespace Bit.Art.Engine
{
    /// <summary>
    /// 根据价格和时间优先级排序匹配策略
    /// </summary>
    /// <remarks>
    /// 参考材料：https://www.cmegroup.com/confluence/display/EPICSANDBOX/Matching+Algorithms#MatchingAlgorithms-FIFO
    /// </remarks>
    public class Program
    {
#if UNITTEST
        public static AutoResetEvent s_autoResetEventForTest { get; private set; } = new AutoResetEvent(false);
#endif
        internal static IConfigurationRoot Configuration { get; set; }

        public static IServiceProvider GlobalServiceProvider { get; set; }

        private static void InitializeConfiguration()
        {
            var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{environment}.json");
            Configuration = builder.Build();
            Utility.Configuration = Configuration;
        }

        public static void Main(string[] args)
        {
            Console.WriteLine("====== ORDER MATCH ======");

            InitializeConfiguration();

            var services = new ServiceCollection();
            services.AddDbContext<ExchangeConfigDb>(options =>
                options.UseMySql(Configuration.GetConnectionString("ExchangeConfigDb")));

            GlobalServiceProvider = services
                .AddLogging()
                .BuildServiceProvider();

            var redisconn = Configuration["redis"];
            var memcache = Memcache.Create(redisconn);
            var tasks = StartEngine(memcache, 500, 100000);
            Task.WaitAll(tasks);
        }

        public static Task[] StartEngine(Memcache cache, int depth, int orderCapacity)
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                .MinimumLevel.Override("System", LogEventLevel.Warning)
                .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
                .Enrich.FromLogContext()
                .WriteTo.File("engine.log", rollingInterval: RollingInterval.Day)
                .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Literate)
                .CreateLogger();
            
            var engine = new OrderMatchEngine();
            // TODO: ringbuffer的大小需要从配置文件里读取
            return engine.Start(cache, 1024, depth, orderCapacity);
        }
    }
}
